package stack_queue;

/**
 * 实现自己的队列
 * 使用链表实现队列
 * 元素类型为 long
 * 使用尾插：入队
 * 使用头删：出队
 */

public class Queue {
    static class Node{
        long val;
        Node next;
        Node(long val){
            this.val = val;
            this.next = null;
        }
    }
    private Node head;
    private Node last;
    private int size;

    public Queue(){
        this.head = this.last = null;
        this.size = 0;
    }

    public void offer(long e){
        Node node = new Node(e);
        if(this.last != null){
            this.last.next = node;
            this.last = node;
        }else{
            this.head = this.last = node;
        }
        this.size++;
    }

    public long poll(){
        if(size == 0){
            throw new RuntimeException("队列为空，不能出队");
        }
        long e = this.head.val;
        this.head = this.head.next;
        if(this.head == null){
            this.last = null;
        }
        size--;
        return e;
    }

    public long peek(){
        if(size == 0){
            throw new RuntimeException("队列为空，不能查看");
        }
        return this.head.val;
    }

    public int size(){
        return this.size;
    }

    public boolean isEmpty(){
        return size() == 0;
    }

    public static void main(String[] args) {
        Queue queue = new Queue();
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);
        System.out.println(queue.poll());       //1
        queue.offer(5);
        System.out.println(queue.peek());       //2
        System.out.println(queue.poll());       //2
        System.out.println(queue.poll());       //3
        System.out.println(queue.poll());       //4
        System.out.println(queue.poll());       //5
        queue.offer(6);
        System.out.println(queue.poll());       //6
        System.out.println(queue.size());       //0

    }
}
